package com.heima.behavior.service.impl;

import com.heima.behavior.dtos.ArticleBehaviorDto;
import com.heima.behavior.service.ApBehaviorServcie;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApBehaviorServcieServcieImpl implements ApBehaviorServcie {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 查询文章行为数据
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleBehaviorDto dto) {
        //1.检查参数
        if (dto.getAuthorId()==null || dto.getArticleId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询用户
        ApUser user= ApThreadLocalUtil.getUser();
        if (user==null){
            return ResponseResult.okResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //游客身份禁止操作
        if (user.getId()==0){
            return ResponseResult.okResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //设置初始值
        boolean isunlike = false, islike = false, iscollection = false, isfollow = false;
        //3.查询收藏行为
        String collection_key="USER_COLLECTION_"+dto.getArticleId();
        iscollection=redisTemplate.opsForHash().hasKey(collection_key,user.getId()+"");
        //查询点赞行为
        String likes_key="USER_LIKES_"+dto.getArticleId();
        islike=redisTemplate.opsForHash().hasKey(likes_key,user.getId()+"");
        //查询关注行为
        String follow_key="USER_FOLLOW_"+user.getId();
        isfollow=redisTemplate.opsForHash().hasKey(follow_key,dto.getAuthorId()+"");
        //查询不喜欢行为
        String unLikes_key="USER_UNLIKES_"+dto.getArticleId();
        isunlike=redisTemplate.opsForHash().hasKey(unLikes_key,user.getId()+"");

        //结果返回
        Map map = new HashMap();
        map.put("isfollow",isfollow);
        map.put("iscollection",iscollection);
        map.put("isunlike",isunlike);
        map.put("islike",islike);

        return ResponseResult.okResult(map);
    }
}
